package com.dituhui.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.dituhui.tool.algorithm.UUIDGenerator;
import com.dituhui.tool.io.Constants;
import com.dituhui.tool.io.ESTool;
import com.dituhui.tool.util.DateUtil;
import com.dituhui.tool.util.StringUtil;

/**
 * 处理上传文件
 * 
 * @author liweigu
 * 
 */
public class DoUploadFile extends HttpServlet {
	private static Logger LOGGER = Logger.getLogger(DoUploadFile.class);
	public static final String PIC = "pic";
	public static final String VIDEO = "video";
	private ServletFileUpload servletFileUpload;
	public static String uploadPicPath = Constants.getValue("uploadPicPath", "web_config.properties");
	public static String uploadPicIndex = Constants.getValue("uploadPicIndex", "web_config.properties");
	public static String uploadVideoPath = Constants.getValue("uploadVideoPath", "web_config.properties");
	public static String uploadVideoIndex = Constants.getValue("uploadVideoIndex", "web_config.properties");
	private String historyESUrl = Constants.getValue("HistoryESUrl", "gps_config.properties");

	public void init() throws ServletException {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		LOGGER.info("uploadFilePath = " + uploadPicPath);
		LOGGER.info("uploadPicIndex = " + uploadPicIndex);
		LOGGER.info("uploadVideoPath = " + uploadVideoPath);
		LOGGER.info("uploadVideoIndex = " + uploadVideoIndex);

		File repository = new File(uploadPicPath);
		factory.setRepository(repository);

		// Create a new file upload handler
		this.servletFileUpload = new ServletFileUpload(factory);
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		StringBuilder output = new StringBuilder();

		// Check that we have a file upload request
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			try {
				LOGGER.info("开始读取上传文件");
				// Parse the request
				List<FileItem> items = servletFileUpload.parseRequest(request);
				LOGGER.info("items.size()=" + items.size());
				String userId = null;
				String coord = null;
				String contentType = null;
				String time = DateUtil.getShortGPSTimeFormat().format(new Date());
				FileItem fileContentItem = null;
				for (FileItem item : items) {
					if (item.isFormField()) {
						String name = item.getFieldName();
						String value = item.getString();
						if ("user".equals(name)) {
							userId = value;
							userId = URLDecoder.decode(userId, "UTF-8");
							// LOGGER.info("userId = " + userId);
						} else if ("coord".equals(name)) {
							coord = value;
						} else if ("contentType".equals(name)) {
							contentType = value;
						}
						LOGGER.info("(FormField)" + name + "=" + value);
					} else {
						fileContentItem = item;
					}
				}
				List<String> fileNames = new ArrayList<String>();
				if(fileContentItem != null){
					String fieldName = fileContentItem.getFieldName();
					LOGGER.info("fieldName=" + fieldName);
					// String fileName = item.getName();
					// String contentType = item.getContentType();
					// boolean isInMemory = item.isInMemory();
					// long sizeInBytes = item.getSize();
					String imgName = UUIDGenerator.generate();
					String subfix = ".png";
					String uploadPath = uploadPicPath;
					if (VIDEO.equalsIgnoreCase(contentType)) {
						subfix = ".mp4";
						uploadPath = uploadVideoPath;
					}
					File uploadedFile = new File(uploadPath + StringUtil.SLASH + imgName + subfix);
					try {
						fileContentItem.write(uploadedFile);
						fileNames.add(imgName);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (fileNames.size() > 0) {
					if (VIDEO.equalsIgnoreCase(contentType)) {
						recordUploadVideoToES(userId, fileNames, coord, time);
					} else {
						recordUploadPicToES(userId, fileNames, coord, time);
					}
					output.append("上传数据成功");
				} else {
					LOGGER.info("无上传文件");
					output.append("无上传文件");
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		} else {
			LOGGER.info("上传数据非法");
			output.append("上传数据非法");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(output.toString());
		out.flush();
		out.close();
	}

	/**
	 * 记录上传照片文件信息到ES
	 * 
	 * @param userId 用户ID
	 * @param imgNames 图片名。如果是多个，则用逗号分隔。
	 * @param coord 坐标
	 * @param time 时间
	 */
	public void recordUploadPicToES(String userId, List<String> imgNames, String coord, String time) {
		String[] columnNames = { "userId", "imgNames", "coord", "time" };
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < imgNames.size(); i++) {
			stringBuilder.append(imgNames.get(i));
			if (i < imgNames.size() - 1) {
				stringBuilder.append(StringUtil.COMMA);
			}
		}
		String[] columnValues = { userId, stringBuilder.toString(), coord, time };
		String result = ESTool.write(this.uploadPicIndex, columnNames, columnValues, this.historyESUrl);
		LOGGER.info("(recordUploadPicToES)写入ES结果：" + result);
	}

	/**
	 * 记录上传视频文件信息到ES
	 * 
	 * @param userId 用户ID
	 * @param videos 图片名。如果是多个，则用逗号分隔。
	 * @param coord 坐标
	 * @param time 时间
	 */
	public void recordUploadVideoToES(String userId, List<String> videos, String coord, String time) {
		String[] columnNames = { "userId", "videoNames", "coord", "time" };
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < videos.size(); i++) {
			stringBuilder.append(videos.get(i));
			if (i < videos.size() - 1) {
				stringBuilder.append(StringUtil.COMMA);
			}
		}
		String[] columnValues = { userId, stringBuilder.toString(), coord, time };
		String result = ESTool.write(this.uploadVideoIndex, columnNames, columnValues, this.historyESUrl);
		LOGGER.info("(recordUploadVideoToES)写入ES结果：" + result);
	}
}
